import 'package:HnXG/Api.dart';
import 'package:HnXG/DIalog.dart';
import 'package:HnXG/Request/Request3.dart';
import 'package:HnXG/Request/Request8.dart';
import 'package:HnXG/Request/TaskAgvRequest.dart';
import 'package:HnXG/snackbar.dart';
import 'package:flutter/material.dart';

class CachePage  extends StatefulWidget{
  const CachePage({super.key});

  @override
  State<StatefulWidget> createState() =>  _CacheStatePage();
}

class _CacheStatePage extends State<CachePage> {
  // 模拟缓存区状态，后期可替换为传入的值
  bool cache1Occupied = false;
  bool cache2Occupied = true;
  // 存储仓库占用状态的列表
  List<bool?> warehouseOccupancy = List.filled(2, null);
 
    @override
  void initState() {
    super.initState();
    fetchWarehouseStatus();
  }
    // 异步方法，通过 Api 类的 GetView_PositionState 接口获取仓库状态
  Future<void> fetchWarehouseStatus() async {
    try {
      final response = await Api.GetView_PositionState(Request3(Type: "缓存区"));
    
      if (response!= null && response['dto'] != null) {
        setState(() {
          for (int i = 0; i < 2; i++) {
            warehouseOccupancy[i] = response['dto'][i]['isExist'];
          }
        });
      }
    } catch (e) {
     
    }
  }

  // 主页面布局
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        title: const Text('小车缓存',
          style: TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.bold,
            shadows: [Shadow(color: Colors.black38, offset: Offset(1,1), blurRadius: 3)],
          )
        ),
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [Colors.blue.shade700, Colors.lightBlue.shade400],
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
            ),
          ),
        ),
        centerTitle: true,
        elevation: 4,
      ),
      body: Padding(
        padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),
        child: SingleChildScrollView(
          physics: const AlwaysScrollableScrollPhysics(),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 仓库进缓存1区域
              const Text('缓存区1任务(手动)', style: TextStyle(fontWeight: FontWeight.bold)),
              const SizedBox(height: 8),
              Wrap(
                spacing: 8,
                children: [
                  // _buildCacheButton('仓库1——>缓存1',"Loc-1-1","Loc-5-1",context),
                  _buildCacheButton('仓库非包装——>缓存',"Loc-1-1","",context),
          
                  // _buildCacheButton('仓库4——>缓存1',"Loc-4-1","Loc-5-1",context),
                ],
              ),
              const SizedBox(height: 20),
              
              // 仓库进缓存2区域
              const Text('缓存区2任务(手动)', style: TextStyle(fontWeight: FontWeight.bold)),
              const SizedBox(height: 8),
              Wrap(
                spacing: 8,
                children: [
                  // _buildCacheButton('仓库1——>缓存2',"Loc-1-1","Loc-6-1",context),
                  // _buildCacheButton('仓库2——>缓存2',"Loc-2-1","Loc-6-1",context),
                  // _buildCacheButton('仓库3——>缓存2',"Loc-3-1","Loc-6-1",context),
                     _buildCacheButton('仓库包装——>缓存',"Loc-4-1","",context),
                ],
              ),

              const SizedBox(height: 15), // 减小间距
              // 新增缓存区状态显示区域
              _buildCacheStatusSection('缓存区1状态', warehouseOccupancy[0]),
              const SizedBox(height: 15), // 减小间距
              _buildCacheStatusSection('缓存区2状态', warehouseOccupancy[1]),
              const SizedBox(height: 15), // 减小底部安全间距
            ],
          ),
        ),
      ),
    );
  }



  /// 缓存按钮样式
  Widget _buildCacheButton(String text,String origination_Code,String target_Code,BuildContext context) {
    return ElevatedButton(
      style: ElevatedButton.styleFrom(
        backgroundColor: Colors.blue, 
        minimumSize: const Size(100, 35), // 减小按钮尺寸
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8)
        ),
      ),
      onPressed: () async {

      final result = await InfoDialog.show(context, "提示信息", "您确定要下发任务吗？");
      if(result==true){
         final response=await Api.CreateToCacheTaskOrder(Request8(Origination_Code: origination_Code));

   if(response['state']==true){
   SuccessSnackBar.show(context, message: response['msg']);
   }
   else{
    ErrorSnackBar.show(context, message: response['msg']);
   }
      
      
      }

 
      }, // 预留点击事件
      child: Text(text, style: const TextStyle(color: Colors.white, fontSize: 14)), // 减小文字大小
    );
  }

  /// 新增缓存区状态显示组件
  Widget _buildCacheStatusSection(String title, bool? isOccupied) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(title, style: const TextStyle(fontWeight: FontWeight.bold)),
        const SizedBox(height: 6), // 减小间距
        Container(
          height: 80, // 减小高度
          width: double.infinity,
          decoration: BoxDecoration(
            color: isOccupied == null ? Colors.white : (isOccupied ? Colors.red : Colors.green),
            borderRadius: BorderRadius.circular(12),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.2),
                blurRadius: 6,
                offset: const Offset(0, 3),
              ),
            ],
          ),
          alignment: Alignment.center,
          child: Text(
            isOccupied == null ? '获取中' : (isOccupied ? '已占用' : '空闲'),
            style: const TextStyle(
              color: Colors.white,
              fontSize: 20, // 减小文字大小
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
      ],
    );
  }
}